import axios from 'axios';

// 创建axios实例
// 由于package.json中配置了proxy，这里不需要设置baseURL
const apiClient = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 避免在登录页面重复跳转
    const isLoginPage = window.location.pathname === '/login';
    
    if (error.response?.status === 401 && !isLoginPage) {
      // Token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    
    // 记录错误信息用于调试
    console.error('API请求错误:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      message: error.message,
      data: error.response?.data
    });
    
    return Promise.reject(error);
  }
);

const authService = {
  // 用户登录
  async login(username, password) {
    try {
      // 参数验证
      if (!username || !password) {
        return {
          success: false,
          message: '用户名和密码不能为空',
        };
      }

      const response = await apiClient.post('/api/v1/auth/login', {
        username,
        password,
      });
      
      // 验证响应数据
      if (!response.data || !response.data.access_token) {
        return {
          success: false,
          message: '服务器响应异常，请稍后重试',
        };
      }

      return {
        success: true,
        token: response.data.access_token,
        user: response.data.user,
      };
    } catch (error) {
      console.error('登录失败:', error);
      
      // 详细的错误处理
      let errorMessage = '登录失败';
      
      try {
        if (error.code === 'ECONNABORTED') {
          errorMessage = '请求超时，请检查网络连接';
        } else if (error.code === 'NETWORK_ERROR' || error.message === 'Network Error') {
          errorMessage = '网络连接失败';
        } else if (error.response) {
          const status = error.response.status;
          const data = error.response.data;
          
          if (status === 401) {
            errorMessage = '用户名或密码错误';
          } else if (status === 403) {
            errorMessage = '账户已被禁用';
          } else if (status === 422) {
            errorMessage = data?.detail || '输入信息格式错误';
          } else if (status === 429) {
            errorMessage = '登录尝试过于频繁，请稍后再试';
          } else if (status >= 500) {
            errorMessage = '服务器暂时不可用，请稍后重试';
          } else {
            errorMessage = data?.detail || data?.message || `请求失败 (${status})`;
          }
        } else if (error.request) {
          errorMessage = '服务器无响应，请检查网络连接';
        }
      } catch (parseError) {
        console.error('解析错误信息时出错:', parseError);
        errorMessage = '登录失败，请稍后重试';
      }
      
      return {
        success: false,
        message: errorMessage,
      };
    }
  },

  // 用户注册
  async register(username, email, password, confirmPassword) {
    try {
      const response = await apiClient.post('/api/v1/auth/register', {
        username,
        email,
        password,
        confirm_password: confirmPassword,
      });
      return {
        success: true,
        message: '注册成功',
        user: response.data.user,
      };
    } catch (error) {
      console.error('注册失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '注册失败',
      };
    }
  },

  // 验证token有效性
  async validateToken(token) {
    try {
      // 如果传入了token，临时设置到localStorage中
      const originalToken = localStorage.getItem('token');
      if (token && token !== originalToken) {
        localStorage.setItem('token', token);
      }
      
      const response = await apiClient.get('/api/v1/auth/me');
      
      // 如果原来没有token或者token不同，恢复原来的token
      if (token && token !== originalToken) {
        if (originalToken) {
          localStorage.setItem('token', originalToken);
        } else {
          localStorage.removeItem('token');
        }
      }
      
      return response.status === 200;
    } catch (error) {
      console.error('Token验证失败:', error);
      return false;
    }
  },

  // 获取当前用户信息
  async getCurrentUser() {
    try {
      const response = await apiClient.get('/api/v1/auth/me');
      return {
        success: true,
        user: response.data,
      };
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '获取用户信息失败',
      };
    }
  },

  // 更新用户信息
  async updateProfile(userData) {
    try {
      const response = await apiClient.put('/api/v1/auth/profile', userData);
      return {
        success: true,
        user: response.data,
      };
    } catch (error) {
      console.error('更新用户信息失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '更新用户信息失败',
      };
    }
  },

  // 修改密码
  async changePassword(passwordData) {
    try {
      const response = await apiClient.put('/api/v1/auth/password', passwordData);
      return {
        success: true,
        message: '密码修改成功',
      };
    } catch (error) {
      console.error('修改密码失败:', error);
      return {
        success: false,
        message: error.response?.data?.detail || '修改密码失败',
      };
    }
  },
};

// 获取用户画像数据
const getUserProfileData = async () => {
  const response = await apiClient.get('/api/v1/auth/profile-data');
  return response.data;
};

// 更新用户画像数据
const updateUserProfileData = async (profileData) => {
  const response = await apiClient.put('/api/v1/auth/profile-data', profileData);
  return response.data;
};

// 创建API对象供其他组件使用
export const authAPI = {
  // 获取当前用户信息
  getCurrentUser: () => apiClient.get('/api/v1/auth/me'),
  
  // 更新用户资料
  updateProfile: (userData) => apiClient.put('/api/v1/auth/profile', userData),
  
  // 修改密码
  changePassword: (passwordData) => apiClient.put('/api/v1/auth/password', passwordData),
  
  // 用户画像相关
  getUserProfileData,
  updateUserProfileData,
};

export default authService;